package org.note.law.controller;

import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.domain.ResponseDTO;
import org.note.law.module.word.LawWord;
import org.note.law.module.word.LawWordService;
import org.note.law.module.word.params.LawWordParams;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("law")
@Api(tags = "法律名词管理")
@AllArgsConstructor
public class LawWordController {
    LawWordService service;

    @SneakyThrows
    @PostMapping("words")
    @ApiOperation(value = "名词新建/更新")
    public ResponseDTO<Object> wordSet(LawWordParams params){
        MultipartFile file = params.getFile();
        if (file.isEmpty()) {
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST, "上传文件不可为空");
        }

        StringBuilder contentSb = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentSb.append(line).append("\n");
            }
        }
        String content = contentSb.toString();
        // 获取对应词
        String word = file.getOriginalFilename();
        if (Validator.isNotEmpty(params.getWord())){
            word = params.getWord();
        }
        LawWord lawWord = new LawWord();
        lawWord.setContent(content);
        lawWord.setWord(word);
        // 匹配，如果已存在需要删除
        service.deleteByWord(word);
        return ResponseDTO.succData(
                service.saveOne(lawWord)
        );
    }
}
